<template>
  <div class="work-order-management">
    <!-- 页面标题和操作 -->
    <div class="page-header">
      <div class="header-left">
        <h1>工单管理</h1>
        <p>生产工单创建、执行、跟踪和管理</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="createWorkOrder">
          <el-icon><Plus /></el-icon>
          新建工单
        </el-button>
        <el-button @click="batchOperation">
          <el-icon><Operation /></el-icon>
          批量操作
        </el-button>
        <el-button @click="exportData">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon pending">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.pending }}</div>
                <div class="stat-label">待执行工单</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon executing">
                <el-icon><VideoPlay /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.executing }}</div>
                <div class="stat-label">执行中工单</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon completed">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.completed }}</div>
                <div class="stat-label">已完成工单</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon efficiency">
                <el-icon><TrendCharts /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.efficiency }}%</div>
                <div class="stat-label">生产效率</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" inline>
        <el-form-item label="工单编号">
          <el-input v-model="filterForm.workOrderNo" placeholder="请输入工单编号" clearable />
        </el-form-item>
        <el-form-item label="产品名称">
          <el-input v-model="filterForm.productName" placeholder="请输入产品名称" clearable />
        </el-form-item>
        <el-form-item label="工单状态">
          <el-select v-model="filterForm.status" placeholder="请选择" clearable>
            <el-option label="待执行" value="pending" />
            <el-option label="执行中" value="executing" />
            <el-option label="已暂停" value="paused" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="车间">
          <el-select v-model="filterForm.workshop" placeholder="请选择" clearable>
            <el-option label="装配车间" value="assembly" />
            <el-option label="机加工车间" value="machining" />
            <el-option label="包装车间" value="packaging" />
            <el-option label="测试车间" value="testing" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划日期">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchWorkOrders">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="resetFilter">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 工单列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>工单列表</span>
          <div class="header-actions">
            <el-button type="text" @click="refreshData">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table
        :data="workOrderData"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        row-key="id"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="expand">
          <template #default="props">
            <div class="expand-content">
              <el-descriptions title="工单详情" :column="3" border>
                <el-descriptions-item label="工艺路线">{{ props.row.processRoute }}</el-descriptions-item>
                <el-descriptions-item label="负责人">{{ props.row.responsible }}</el-descriptions-item>
                <el-descriptions-item label="创建时间">{{ props.row.createTime }}</el-descriptions-item>
                <el-descriptions-item label="备注" :span="3">{{ props.row.remark || '无' }}</el-descriptions-item>
              </el-descriptions>
              
              <div class="process-steps" v-if="props.row.processSteps">
                <h4>工艺步骤</h4>
                <el-steps :active="props.row.currentStep" align-center>
                  <el-step
                    v-for="(step, index) in props.row.processSteps"
                    :key="index"
                    :title="step.name"
                    :description="step.description"
                    :status="getStepStatus(index, props.row.currentStep)"
                  />
                </el-steps>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="workOrderNo" label="工单编号" width="140" fixed="left" />
        <el-table-column prop="productName" label="产品名称" min-width="150" />
        <el-table-column prop="productCode" label="产品编码" width="120" />
        <el-table-column prop="plannedQuantity" label="计划数量" width="100" align="right" />
        <el-table-column prop="completedQuantity" label="完成数量" width="100" align="right" />
        <el-table-column prop="progress" label="进度" width="120">
          <template #default="scope">
            <el-progress :percentage="scope.row.progress" :stroke-width="8" />
          </template>
        </el-table-column>
        <el-table-column prop="workshop" label="车间" width="120">
          <template #default="scope">
            <el-tag :type="getWorkshopType(scope.row.workshop)">{{ getWorkshopText(scope.row.workshop) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="scope">
            <el-tag :type="getPriorityType(scope.row.priority)">{{ scope.row.priority }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="planStartDate" label="计划开始" width="120" />
        <el-table-column prop="planEndDate" label="计划完成" width="120" />
        <el-table-column prop="actualStartDate" label="实际开始" width="120" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="text" size="small" @click="viewWorkOrder(scope.row)">
              查看
            </el-button>
            <el-button type="text" size="small" @click="editWorkOrder(scope.row)">
              编辑
            </el-button>
            <el-dropdown @command="handleCommand">
              <el-button type="text" size="small">
                更多<el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{action: 'start', row: scope.row}">
                    开始执行
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'pause', row: scope.row}">
                    暂停
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'resume', row: scope.row}">
                    恢复
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'complete', row: scope.row}">
                    完成
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'cancel', row: scope.row}" divided>
                    取消
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'delete', row: scope.row}">
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新建/编辑工单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="900px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="workOrderFormRef"
        :model="workOrderForm"
        :rules="workOrderFormRules"
        label-width="120px"
      >
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="产品" prop="productId">
                  <el-select
                    v-model="workOrderForm.productId"
                    placeholder="请选择产品"
                    filterable
                    @change="handleProductChange"
                  >
                    <el-option
                      v-for="product in productOptions"
                      :key="product.id"
                      :label="product.name"
                      :value="product.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="生产数量" prop="plannedQuantity">
                  <el-input-number
                    v-model="workOrderForm.plannedQuantity"
                    :min="1"
                    :max="999999"
                    placeholder="请输入生产数量"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="车间" prop="workshop">
                  <el-select v-model="workOrderForm.workshop" placeholder="请选择车间">
                    <el-option label="装配车间" value="assembly" />
                    <el-option label="机加工车间" value="machining" />
                    <el-option label="包装车间" value="packaging" />
                    <el-option label="测试车间" value="testing" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="优先级" prop="priority">
                  <el-select v-model="workOrderForm.priority" placeholder="请选择优先级">
                    <el-option label="高" value="高" />
                    <el-option label="中" value="中" />
                    <el-option label="低" value="低" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="计划开始" prop="planStartDate">
                  <el-date-picker
                    v-model="workOrderForm.planStartDate"
                    type="datetime"
                    placeholder="请选择计划开始时间"
                    format="YYYY-MM-DD HH:mm"
                    value-format="YYYY-MM-DD HH:mm"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="计划完成" prop="planEndDate">
                  <el-date-picker
                    v-model="workOrderForm.planEndDate"
                    type="datetime"
                    placeholder="请选择计划完成时间"
                    format="YYYY-MM-DD HH:mm"
                    value-format="YYYY-MM-DD HH:mm"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item label="负责人" prop="responsible">
              <el-select v-model="workOrderForm.responsible" placeholder="请选择负责人" filterable>
                <el-option label="张三" value="张三" />
                <el-option label="李四" value="李四" />
                <el-option label="王五" value="王五" />
                <el-option label="赵六" value="赵六" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="备注">
              <el-input
                v-model="workOrderForm.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-tab-pane>
          
          <el-tab-pane label="工艺路线" name="process">
            <div class="process-route-section">
              <div class="section-header">
                <span>工艺步骤</span>
                <el-button type="primary" size="small" @click="addProcessStep">
                  <el-icon><Plus /></el-icon>
                  添加步骤
                </el-button>
              </div>
              
              <div class="process-steps-list">
                <div
                  v-for="(step, index) in workOrderForm.processSteps"
                  :key="index"
                  class="process-step-item"
                >
                  <div class="step-number">{{ index + 1 }}</div>
                  <div class="step-content">
                    <el-row :gutter="12">
                      <el-col :span="8">
                        <el-input v-model="step.name" placeholder="步骤名称" />
                      </el-col>
                      <el-col :span="10">
                        <el-input v-model="step.description" placeholder="步骤描述" />
                      </el-col>
                      <el-col :span="4">
                        <el-input-number
                          v-model="step.duration"
                          placeholder="工时(小时)"
                          :min="0.1"
                          :step="0.1"
                          style="width: 100%"
                        />
                      </el-col>
                      <el-col :span="2">
                        <el-button type="danger" size="small" @click="removeProcessStep(index)">
                          <el-icon><Delete /></el-icon>
                        </el-button>
                      </el-col>
                    </el-row>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="物料清单" name="materials">
            <div class="materials-section">
              <div class="section-header">
                <span>所需物料</span>
                <el-button type="primary" size="small" @click="addMaterial">
                  <el-icon><Plus /></el-icon>
                  添加物料
                </el-button>
              </div>
              
              <el-table :data="workOrderForm.materials" style="width: 100%">
                <el-table-column prop="materialCode" label="物料编码" width="120" />
                <el-table-column prop="materialName" label="物料名称" min-width="150" />
                <el-table-column prop="specification" label="规格" width="120" />
                <el-table-column prop="unit" label="单位" width="80" />
                <el-table-column prop="requiredQuantity" label="需求数量" width="100" align="right" />
                <el-table-column prop="availableQuantity" label="可用库存" width="100" align="right" />
                <el-table-column label="操作" width="80">
                  <template #default="scope">
                    <el-button type="danger" size="small" @click="removeMaterial(scope.$index)">
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveWorkOrder" :loading="saving">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Operation,
  Download,
  Search,
  Refresh,
  ArrowDown,
  Clock,
  VideoPlay,
  CircleCheck,
  TrendCharts,
  Delete
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const workOrderFormRef = ref(null)
const selectedWorkOrders = ref([])
const activeTab = ref('basic')

// 统计数据
const stats = reactive({
  pending: 15,
  executing: 8,
  completed: 42,
  efficiency: 85
})

// 筛选表单
const filterForm = reactive({
  workOrderNo: '',
  productName: '',
  status: '',
  workshop: '',
  dateRange: []
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 工单表单
const workOrderForm = reactive({
  id: null,
  productId: '',
  plannedQuantity: 1,
  workshop: '',
  priority: '中',
  planStartDate: '',
  planEndDate: '',
  responsible: '',
  remark: '',
  processSteps: [
    { name: '备料', description: '准备生产所需物料', duration: 1 },
    { name: '加工', description: '按工艺要求进行加工', duration: 4 },
    { name: '装配', description: '组装产品部件', duration: 2 },
    { name: '测试', description: '产品功能测试', duration: 1 }
  ],
  materials: [
    {
      materialCode: 'M001',
      materialName: '主板',
      specification: 'V2.1',
      unit: '片',
      requiredQuantity: 100,
      availableQuantity: 150
    },
    {
      materialCode: 'M002',
      materialName: '外壳',
      specification: '黑色',
      unit: '个',
      requiredQuantity: 100,
      availableQuantity: 80
    }
  ]
})

// 表单验证规则
const workOrderFormRules = {
  productId: [{ required: true, message: '请选择产品', trigger: 'change' }],
  plannedQuantity: [{ required: true, message: '请输入生产数量', trigger: 'blur' }],
  workshop: [{ required: true, message: '请选择车间', trigger: 'change' }],
  priority: [{ required: true, message: '请选择优先级', trigger: 'change' }],
  planStartDate: [{ required: true, message: '请选择计划开始时间', trigger: 'change' }],
  planEndDate: [{ required: true, message: '请选择计划完成时间', trigger: 'change' }],
  responsible: [{ required: true, message: '请选择负责人', trigger: 'change' }]
}

// 产品选项
const productOptions = ref([
  { id: 1, name: '智能手机主板', code: 'MB001' },
  { id: 2, name: '电源适配器', code: 'PA001' },
  { id: 3, name: '数据线', code: 'DC001' },
  { id: 4, name: '保护壳', code: 'PC001' },
  { id: 5, name: '耳机', code: 'HP001' }
])

// 工单数据
const workOrderData = ref([
  {
    id: 1,
    workOrderNo: 'WO202501001',
    productName: '智能手机主板',
    productCode: 'MB001',
    plannedQuantity: 1000,
    completedQuantity: 750,
    progress: 75,
    workshop: 'assembly',
    status: 'executing',
    priority: '高',
    planStartDate: '2025-01-15',
    planEndDate: '2025-01-25',
    actualStartDate: '2025-01-15',
    processRoute: '标准装配流程',
    responsible: '张三',
    createTime: '2025-01-14 09:00:00',
    currentStep: 2,
    processSteps: [
      { name: '备料', description: '准备生产所需物料' },
      { name: '加工', description: '按工艺要求进行加工' },
      { name: '装配', description: '组装产品部件' },
      { name: '测试', description: '产品功能测试' }
    ],
    remark: '紧急订单，优先生产'
  },
  {
    id: 2,
    workOrderNo: 'WO202501002',
    productName: '电源适配器',
    productCode: 'PA001',
    plannedQuantity: 500,
    completedQuantity: 200,
    progress: 40,
    workshop: 'machining',
    status: 'executing',
    priority: '中',
    planStartDate: '2025-01-18',
    planEndDate: '2025-01-28',
    actualStartDate: '2025-01-18',
    processRoute: '机加工流程',
    responsible: '李四',
    createTime: '2025-01-17 14:30:00',
    currentStep: 1,
    processSteps: [
      { name: '备料', description: '准备生产所需物料' },
      { name: '机加工', description: '精密机械加工' },
      { name: '表面处理', description: '表面喷涂处理' },
      { name: '质检', description: '质量检验' }
    ],
    remark: '常规生产计划'
  },
  {
    id: 3,
    workOrderNo: 'WO202501003',
    productName: '数据线',
    productCode: 'DC001',
    plannedQuantity: 2000,
    completedQuantity: 2000,
    progress: 100,
    workshop: 'packaging',
    status: 'completed',
    priority: '中',
    planStartDate: '2025-01-10',
    planEndDate: '2025-01-20',
    actualStartDate: '2025-01-10',
    processRoute: '包装流程',
    responsible: '王五',
    createTime: '2025-01-09 10:15:00',
    currentStep: 4,
    processSteps: [
      { name: '备料', description: '准备生产所需物料' },
      { name: '组装', description: '线材组装' },
      { name: '测试', description: '功能测试' },
      { name: '包装', description: '产品包装' }
    ],
    remark: '已完成生产'
  }
])

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    pending: 'info',
    executing: 'primary',
    paused: 'warning',
    completed: 'success',
    cancelled: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '待执行',
    executing: '执行中',
    paused: '已暂停',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

// 获取车间类型
const getWorkshopType = (workshop) => {
  const workshopMap = {
    assembly: 'primary',
    machining: 'success',
    packaging: 'warning',
    testing: 'info'
  }
  return workshopMap[workshop] || 'info'
}

// 获取车间文本
const getWorkshopText = (workshop) => {
  const workshopMap = {
    assembly: '装配车间',
    machining: '机加工车间',
    packaging: '包装车间',
    testing: '测试车间'
  }
  return workshopMap[workshop] || workshop
}

// 获取优先级类型
const getPriorityType = (priority) => {
  const priorityMap = {
    '高': 'danger',
    '中': 'warning',
    '低': 'info'
  }
  return priorityMap[priority] || 'info'
}

// 获取步骤状态
const getStepStatus = (stepIndex, currentStep) => {
  if (stepIndex < currentStep) return 'finish'
  if (stepIndex === currentStep) return 'process'
  return 'wait'
}

// 事件处理函数
const searchWorkOrders = () => {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    loading.value = false
    ElMessage.success('查询完成')
  }, 1000)
}

const resetFilter = () => {
  Object.assign(filterForm, {
    workOrderNo: '',
    productName: '',
    status: '',
    workshop: '',
    dateRange: []
  })
  searchWorkOrders()
}

const refreshData = () => {
  searchWorkOrders()
}

const createWorkOrder = () => {
  dialogTitle.value = '新建工单'
  resetWorkOrderForm()
  dialogVisible.value = true
}

const editWorkOrder = (row) => {
  dialogTitle.value = '编辑工单'
  Object.assign(workOrderForm, {
    id: row.id,
    productId: getProductIdByName(row.productName),
    plannedQuantity: row.plannedQuantity,
    workshop: row.workshop,
    priority: row.priority,
    planStartDate: row.planStartDate,
    planEndDate: row.planEndDate,
    responsible: row.responsible,
    remark: row.remark
  })
  dialogVisible.value = true
}

const viewWorkOrder = (row) => {
  ElMessage.info(`查看工单：${row.workOrderNo}`)
}

const handleCommand = (command) => {
  const { action, row } = command
  switch (action) {
    case 'start':
      ElMessage.success(`开始执行工单：${row.workOrderNo}`)
      break
    case 'pause':
      ElMessage.warning(`暂停工单：${row.workOrderNo}`)
      break
    case 'resume':
      ElMessage.success(`恢复工单：${row.workOrderNo}`)
      break
    case 'complete':
      ElMessage.success(`完成工单：${row.workOrderNo}`)
      break
    case 'cancel':
      ElMessageBox.confirm('确定要取消此工单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        ElMessage.success(`取消工单：${row.workOrderNo}`)
      })
      break
    case 'delete':
      ElMessageBox.confirm('确定要删除此工单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        ElMessage.success(`删除工单：${row.workOrderNo}`)
      })
      break
  }
}

const handleSelectionChange = (selection) => {
  selectedWorkOrders.value = selection
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  searchWorkOrders()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  searchWorkOrders()
}

const handleDialogClose = () => {
  resetWorkOrderForm()
}

const handleProductChange = (productId) => {
  // 根据产品变化更新相关信息
  console.log('Selected product:', productId)
}

const saveWorkOrder = () => {
  workOrderFormRef.value.validate((valid) => {
    if (valid) {
      saving.value = true
      // 模拟API调用
      setTimeout(() => {
        saving.value = false
        dialogVisible.value = false
        ElMessage.success(workOrderForm.id ? '更新成功' : '创建成功')
        searchWorkOrders()
      }, 1000)
    }
  })
}

const batchOperation = () => {
  if (selectedWorkOrders.value.length === 0) {
    ElMessage.warning('请先选择工单')
    return
  }
  ElMessage.success('批量操作功能开发中')
}

const exportData = () => {
  ElMessage.success('导出功能开发中')
}

const addProcessStep = () => {
  workOrderForm.processSteps.push({
    name: '',
    description: '',
    duration: 1
  })
}

const removeProcessStep = (index) => {
  workOrderForm.processSteps.splice(index, 1)
}

const addMaterial = () => {
  workOrderForm.materials.push({
    materialCode: '',
    materialName: '',
    specification: '',
    unit: '',
    requiredQuantity: 0,
    availableQuantity: 0
  })
}

const removeMaterial = (index) => {
  workOrderForm.materials.splice(index, 1)
}

// 辅助函数
const resetWorkOrderForm = () => {
  Object.assign(workOrderForm, {
    id: null,
    productId: '',
    plannedQuantity: 1,
    workshop: '',
    priority: '中',
    planStartDate: '',
    planEndDate: '',
    responsible: '',
    remark: '',
    processSteps: [
      { name: '备料', description: '准备生产所需物料', duration: 1 },
      { name: '加工', description: '按工艺要求进行加工', duration: 4 },
      { name: '装配', description: '组装产品部件', duration: 2 },
      { name: '测试', description: '产品功能测试', duration: 1 }
    ],
    materials: [
      {
        materialCode: 'M001',
        materialName: '主板',
        specification: 'V2.1',
        unit: '片',
        requiredQuantity: 100,
        availableQuantity: 150
      }
    ]
  })
  workOrderFormRef.value?.clearValidate()
  activeTab.value = 'basic'
}

const getProductIdByName = (name) => {
  const product = productOptions.value.find(p => p.name === name)
  return product ? product.id : ''
}

// 生命周期
onMounted(() => {
  searchWorkOrders()
  pagination.total = workOrderData.value.length
})
</script>

<style scoped>
.work-order-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.header-left h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.header-left p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.header-right {
  display: flex;
  gap: 12px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.stat-icon.pending {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.executing {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.completed {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-icon.efficiency {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
}

.filter-card,
.table-card {
  margin-bottom: 20px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.expand-content {
  padding: 20px;
  background-color: #fafafa;
}

.process-steps {
  margin-top: 20px;
}

.process-steps h4 {
  margin: 0 0 16px 0;
  color: #303133;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.process-route-section,
.materials-section {
  margin-top: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  font-weight: 600;
  color: #303133;
}

.process-steps-list {
  max-height: 300px;
  overflow-y: auto;
}

.process-step-item {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.step-number {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  flex-shrink: 0;
}

.step-content {
  flex: 1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .work-order-management {
    padding: 12px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .header-right {
    width: 100%;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
  
  .stats-cards .el-col {
    margin-bottom: 12px;
  }
  
  .el-form--inline .el-form-item {
    display: block;
    margin-right: 0;
    margin-bottom: 16px;
  }
}
</style>